package net.jueb.protobufs2.server;
import net.jueb.protobufs2.pojo.MessageProto.Message;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ProtobufServer {
	
	public void start(int port)
	{
		NioEventLoopGroup boss=new NioEventLoopGroup();
		NioEventLoopGroup worker=new NioEventLoopGroup();
		ServerBootstrap sbt=new ServerBootstrap();
		sbt.group(boss, worker);
		sbt.channel(NioServerSocketChannel.class);
		sbt.option(ChannelOption.SO_BACKLOG, 65536);
		sbt.handler(new LoggingHandler(LogLevel.INFO));
		sbt.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				//半包处理handler
				sc.pipeline().addLast(new ProtobufVarint32FrameDecoder());
				//解码器
				sc.pipeline().addLast(new ProtobufDecoder(Message.getDefaultInstance()));
				
				//半包处理handler
				sc.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
				//编码器
				sc.pipeline().addLast(new ProtobufEncoder());
				
				//业务处理handler
				sc.pipeline().addLast(new ProtobufServerHandler());
			}
		});
		try {
			ChannelFuture cf=sbt.bind(port).sync();//等待绑定成功
			cf.channel().closeFuture().sync();//等待关闭
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new ProtobufServer().start(80);
	}
}
